﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.Linq;
using System.IO;
using Ue.Extensions;

namespace Ue.Eagle.Runtime.Configuration
{
    public class PluginExtensionCollection : ConfigurationElementCollection
    {
        //public override ConfigurationElementCollectionType CollectionType
        //{
        //    get { return ConfigurationElementCollectionType.BasicMap; }
        //}

        //protected override string ElementName
        //{
        //    get { return PluginConfigurationConstants.PluginExtensionElementName; }
        //}

        protected override ConfigurationElement CreateNewElement()
        {
            return new PluginExtensionElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return Guid.NewGuid();
        }

        protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
        {
            if (this.ElementName.Equals(elementName) || elementName.Equals("add"))
            {
                var pointIdPair = reader.GetAttributeValues().SingleOrDefault(item => item.Key.Equals(PluginConfigurationConstants.PluginExtensionPointIdAttributeName));
                if (!string.IsNullOrEmpty(pointIdPair.Value))
                {
                    var element = new PluginExtensionElement();
                    element.PointId = pointIdPair.Value;
                    element.ElementOuterXml = reader.ReadOuterXml();

                    base.BaseAdd(element);
                }

                return true;
            }

            return base.OnDeserializeUnrecognizedElement(elementName, reader);
        }
    }
}
